<?php

App::uses('AppController', 'Controller');

class LocationsController extends AppController {
    
    public $pageTitle = "Lokacije";

    public $uses = array('Location', 'AdType');

    private $joinSQL = '';
    public $paginate = array(
    'fields'=> array('Location.*'),
        'limit' => ITEMS_PER_PAGE,
        'group' => 'Location.id',
        'joins' => array(),
    'recursive' => false
    );
    
    private function buildJoinSQL($search) {
        $clSQL = '
            CampaignsLocation.start <= NOW() AND
            CampaignsLocation.end   >= NOW()
        ';
        $lrSQL = '
            LocationReservation.start <= NOW() AND
            LocationReservation.end   >= NOW()
        ';
        
        if (!empty($search['from']) && !empty($search['to'])) {
            $from = $search['from'];
            $to   = $search['to'];
            
            $clSQL = '('.
                    "(CampaignsLocation.start BETWEEN '{$from}' AND '{$to}')".
                ' OR '.
                    "(CampaignsLocation.end BETWEEN '{$from}' AND '{$to}')".
                ' OR '.
                    "(CampaignsLocation.start < '{$from}' AND CampaignsLocation.end > '{$to}')".
                ')';
            
            $lrSQL = '('.
                    "(LocationReservation.start BETWEEN '{$from}' AND '{$to}')".
                ' OR '.
                    "(LocationReservation.end BETWEEN '{$from}' AND '{$to}')".
                ' OR '.
                    "(LocationReservation.start < '{$from}' AND LocationReservation.end > '{$to}')".
                ')';
        }
        
        $this->joinSQL = '
            LEFT JOIN (
                campaigns_locations CampaignsLocation
                INNER JOIN campaigns Campaign ON (
                    Campaign.id=CampaignsLocation.campaign_id AND
                    '.$clSQL.'
                )
            ) ON CampaignsLocation.location_id=Location.id
            LEFT JOIN location_reservations LocationReservation ON (
                LocationReservation.location_id=Location.id AND
                '.$lrSQL.'
            )
        JOIN (
        locations_ad_types LocationAdType
        JOIN ad_types AdType ON AdType.id=LocationAdType.ad_type_id
        ) ON Location.id = LocationAdType.location_id
        ';
    }
    
    private function _list($conditions = array()) {
        $filter = $this->parseFilterData('Location');
        $this->setFilterData($filter);
        
        $conditions = array_merge($filter->conditions, $conditions);
        if (! empty($conditions)) {
            $this->paginate['limit'] = 9999;
        }
        $this->paginate['joins'] = array($this->joinSQL);
        $this->paginate['order'] = "{$filter->sortBy} {$filter->sortDir}";

        $locations = $this->paginate('Location', $conditions);
        
        foreach ($locations as &$location) {
            // load ad types    
            $at = $this->Location->loadAdTypes($location);
            $location['AdType'] = $at['AdType'];
            
            // load price
            $pr = $this->Location->loadPrice($location);
            $location['Location']['price'] = $pr;
        }
        $this->set('locations', $locations);
        //debug($this->Location->getDataSource()->getLog());
    }
    public function index() {
        $conditions = array();
        $search = @$this->data['Search'];
        
        $this->buildJoinSQL($search);
        
        //conditions
        if (! empty($search)) {
            if ( !empty($search['from']) && !empty($search['to'])) {
                $this->Location->dateRange = array($search['from'], $search['to']);
                switch($search['status']) {
                    case 'free':
                        $conditions = array('Campaign.id' => null, 'LocationReservation.id' => null);
                        break;
                        
                    case 'reserved':
                        $conditions = array('LocationReservation.id !=' => null);
                        break;
                        
                    case 'occupied':
                        $conditions = array('Campaign.id !=' => null);
                        break;
                }
            }
        }
        
        $this->_list($conditions);
    }

    public function free() {
        $this->_list('free', array('Campaign.id' => null, 'LocationReservation.id' => null));
        $this->render('index');
    }
    public function reserved() {
        $this->_list('reserved', array('LocationReservation.id !=' => null));
        $this->render('index');
    }
    public function occupied() {
        $this->_list('occupied', array('Campaign.id !=' => null));
        $this->render('index');
    }
    
    public function lista() {
        $this->layout = 'ajax';
        $this->set('locations', $this->Location->find('all'));
    }
    
    private function setCommonData() {
        $this->set('ad_types', $this->AdType->find('list'));
    }
    
    public function create() {
        $this->setCommonData();
        $this->set('data', $this->Location->create());
        $this->render('form');
    }
    
    public function edit($id) {
        $this->setCommonData();
        $this->set('data', $this->Location->findById($id));
        $this->render('form');
    }
    
    public function save() {
        $data = @$this->data;
        if (! empty($data)) {
            
            $toUpload = array();
            if (!isset($data['LocationImage'])) {
                $data['LocationImage'] = array();
            }
            foreach ($data['Location']['NewLocationImage'] as $newPhoto) {
                if (! $newPhoto['error']) {
                    $toUpload[] = $newPhoto;
                    $data['LocationImage'][] = array(
                        'image' => $newPhoto['name'],
                        'position' => count($data['LocationImage'])
                    );
                }
            }
            
            $saved = true;
            $this->Location->create($data);
            if (! $this->Location->validates()) {
                $saved   = false;
                $message = 'Uneti podaci nisu validni';
            } else {
                if ($data['Location']['id'] > 0) {
                    $this->Location->LocationImage->deleteAll(array(
                        "LocationImage.location_id" => $data['Location']['id']
                    ));
                }
                $this->Location->deleteRelatedData();
                if (! $this->Location->saveAll($data)) {
                    $saved   = false;
                    $message = 'Došlo je do greške pri čuvanju podataka';
                }
            }
            
            if ($saved) {
                
                if (! empty($toUpload)) {
                    upload_files($toUpload, 'img' . DS . 'locations' . DS . $this->Location->id);
                }
                
                $data   = $this->Location->findById($this->Location->id);
                $images = Set::extract($data, 'LocationImage.{n}.image');
                remove_other_files($images, 'img' . DS . 'locations' . DS . $this->Location->id);
                
                $this->setFlash('Lokacija je sačuvana', 'ok');
                $this->redirect('/locations/edit/' . $this->Location->id);
            } else {
                $this->setFlash($message);
                $this->setCommonData();
                $this->set('data', $data);
                return $this->render('form');
            }
        }
        $this->redirect("index");
    }

    public function remove($id) {
        if ($this->Location->delete($id)) {
            remove_dir('img' . DS . 'locations' . DS . $id);
            $this->setFlash('Lokacija je obrisana', 'ok');
        } else {
            $this->setFlash('Lokacija nije obrisana');
        }
        $this->redirect("index");
    }
    
    public function get_status() {
        $this->autoRender = false;

        $ids = $this->params['pass'];
        if (empty($ids)) {
            return;
        }

        $status = $this->Location->getStatus($ids);
        echo json_encode($status);
    }
}
